package cn.ezios.huo.system.dao.service.impl;

import cn.ezios.huo.common.utils.PasswordCall;
import cn.ezios.huo.system.dao.dto.SysUserDTO;
import cn.ezios.huo.system.dao.vo.SysUserVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ezios.huo.system.dao.domain.SysUser;
import cn.ezios.huo.system.dao.service.SysUserService;
import cn.ezios.huo.system.dao.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author 王坚
 * @description 针对表【sys_user(系统用户表)】的数据库操作Service实现
 * @createDate 2024-07-17 09:49:16
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    /**
     * 分页查询
     *
     * @param current
     * @param size
     * @param dto
     * @return
     */
    @Override
    public IPage<SysUserVO> queryPage(Integer current, Integer size, SysUserDTO dto) {
        Page<SysUser> page = Page.of(current, size);
        return lambdaQuery()
                .like(dto.getNickName() != null && !dto.getNickName().isBlank(), SysUser::getNickName, dto.getNickName())
                .like(dto.getLoginName() != null && !dto.getLoginName().isBlank(), SysUser::getLoginName, dto.getLoginName())
                .like(dto.getPhone() != null && !dto.getPhone().isBlank(), SysUser::getPhone, dto.getPhone())
                .orderByDesc(SysUser::getCreatedTime)
                .page(page)
                .convert(origin -> {
                    SysUserVO vo = new SysUserVO();
                    BeanUtils.copyProperties(origin, vo);
                    return vo;
                });
    }

    /**
     * 新增用户
     *
     * @param sysUserDTO
     * @return
     */
    @Override
    public boolean createUser(SysUserDTO sysUserDTO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDTO, sysUser);
        sysUser.setPassword(PasswordCall.generatePassword(sysUser.getPassword()));
        return save(sysUser);
    }

    /**
     * 修改用户
     *
     * @param sysUserDTO
     * @return
     */
    @Override
    public boolean updateUser(SysUserDTO sysUserDTO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDTO, sysUser);
        if(sysUser.getPassword()!=null&&!sysUser.getPassword().isBlank()){
            sysUser.setPassword(PasswordCall.generatePassword(sysUser.getPassword()));
        }
        return updateById(sysUser);
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public SysUserVO getUserById(String id) {
        SysUser sysUser = getById(id);
        if (sysUser != null) {
            SysUserVO vo = new SysUserVO();
            BeanUtils.copyProperties(sysUser, vo);
            return vo;
        }
        return null;
    }


}




